﻿package com.dao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.pro.bean.Info;

public class ObjectDao extends BaseDao {

	public final static int NOTINSERTID = 1;
	public final static int INSERTALL = 0;

	@Override
	protected List fetchMultiResults(ResultSet rs, Object clas)
			throws SQLException {
		// TODO Auto-generated method stub
		ArrayList resultList = new ArrayList();
		try {
			// System.out.println("序列化result ING");
			while (rs.next()) {
				// System.out.println("RS不等于null");
				Object bean = Class.forName(clas.getClass().getName())
						.newInstance();
				// Info bean = new Info();
				populateVO(bean, rs);
				resultList.add(bean);
			}
		} catch (Exception e) {
		}
		return resultList;
	}

	/**
	 * 插入数据
	 * 
	 * @param o
	 * @param insertArg
	 *            (Object.INSERTALL or Object.NOTINSERTID)
	 * @return count
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 */
	public int add(Object o, int insertArg) throws SecurityException,
			NoSuchMethodException {
		List params = new ArrayList();
		int cc = 0;
		String name = o.getClass().getName();
		String ss[] = name.split("\\.");
		String tableName = ss[ss.length - 1];
		String sql = "INSERT INTO " + tableName;
		/*
		 * + "(cmp,cmpeng,cmppinyin,dept,post,firstname," +
		 * "secondname,firstnamepy,secondnamepy,zipcode1,province1," +
		 * "city1,region1,address1,telfirst1,telsecond1,fax1,mobiletel1," +
		 * "email1,url1,zipcode2,province2,city2,region2,address2,telfirst2," +
		 * "telsecond2,fax2,mobiletel2,email2,url2,important,job,relation," +
		 * "sex,blood,birthday,memo,business,cmpfddate,capital,empnum,bondcode,repname,"
		 * + "crtdate,crtuser,crtcmp,uptime,upusr,upcmp)" +
		 * "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," +
		 * "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		 */
		Field field[] = o.getClass().getDeclaredFields();
		// Method methods[] = o.getClass().getDeclaredMethod(tableName,
		// parameterTypes);
		sql += "(";
		// 拼接 sql
		for (int i = insertArg; i < field.length - 1; ++i) {
			// System.out.println(field[i].getName());
			sql += field[i].getName() + ",";
		}
		sql += field[field.length - 1].getName() + ")";
		sql += "VALUES (";
		for (int i = insertArg; i < field.length - 1; ++i) {
			sql += "?,";
		}

		System.out.println("add sql --> " + sql);

		for (int i = insertArg; i < field.length; ++i) {
			// Method f = methods[i];
			String fieldname = field[i].getName();
			char c = fieldname.charAt(0);
			fieldname = (c + "").toUpperCase() + fieldname.substring(1);
			// System.out.println(fieldname);
			Method f = o.getClass().getDeclaredMethod("get" + fieldname, null);
			if (f.getName().startsWith("get")
			// && f.getName().indexOf("Cardid") == -1
					&& f.getParameterTypes().length == 0) {
				try {
					//System.out.println("i = " + i + " " + (cc++) + " : "
					//		+ f.getName() + " rs : " + f.invoke(o, null));
					params.add(f.invoke(o, null));
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else
				System.out.println("ELSExxx " + f.getName());
		}

		sql += "?)";

		System.out.println("sql --> " + sql);
		int count = super.executeSQL(sql, params);
		return count;
	}

	/*
	 * 删除主键id匹配的条目；
	 */
	public int delete(int id, Object clas) {
		String name = clas.getClass().getName();
		String ss[] = name.split("\\.");
		String tableName = ss[ss.length - 1];
		Field field[] = clas.getClass().getDeclaredFields();
		String pkstr = field[0].getName();
		String sql = "delete from " + tableName + " where " + pkstr + "=" + id;
		System.out.println("sql delete id -->" + sql);
		int count = super.executeSQL(sql, null);
		return count;
	}

	public List find(int id, Object clas) {
		String name = clas.getClass().getName();
		String ss[] = name.split("\\.");
		String tableName = ss[ss.length - 1];
		Field field[] = clas.getClass().getDeclaredFields();
		String pkstr = field[0].getName();
		String sql = "select * from " + tableName + " where " + pkstr + "="
				+ id;
		System.out.println("sql find id -->" + sql);
		return super.findAll(sql, clas);
	}

	public List findall(Object clas) {
		String name = clas.getClass().getName();
		String ss[] = name.split("\\.");
		String tableName = ss[ss.length - 1];
		String sql = "select * from " + tableName;
		System.out.println("sql findall -->" + sql);
		return super.findAll(sql, clas);
	}

	public int updates(Object o) throws IllegalAccessException,
			InvocationTargetException, SecurityException, NoSuchMethodException {

		// List params = new ArrayList();
		int cc = 0;
		String name = o.getClass().getName();
		String ss[] = name.split("\\.");
		String tableName = ss[ss.length - 1];
		String sql = "UPDATE " + tableName;
		/*
		 * + "(cmp,cmpeng,cmppinyin,dept,post,firstname," +
		 * "secondname,firstnamepy,secondnamepy,zipcode1,province1," +
		 * "city1,region1,address1,telfirst1,telsecond1,fax1,mobiletel1," +
		 * "email1,url1,zipcode2,province2,city2,region2,address2,telfirst2," +
		 * "telsecond2,fax2,mobiletel2,email2,url2,important,job,relation," +
		 * "sex,blood,birthday,memo,business,cmpfddate,capital,empnum,bondcode,repname,"
		 * + "crtdate,crtuser,crtcmp,uptime,upusr,upcmp)" +
		 * "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," +
		 * "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		 */
		Field field[] = o.getClass().getDeclaredFields();
		Method methods[] = o.getClass().getDeclaredMethods();
		String id;
		// for(int i=0;i<methods.length;++i)
		// {
		// if(methods[i].getName().toUpperCase().indexOf(
		// field[0].getName().toUpperCase()) != -1)
		// id =
		// }
		sql += " SET ";
		// 拼接 sql
		for (int i = 1; i < field.length; ++i) {
			//System.out.println(field[i].getName());
			String fieldname = field[i].getName();
			char c = fieldname.charAt(0);
			fieldname = (c + "").toUpperCase() + fieldname.substring(1);
			Method f = o.getClass().getDeclaredMethod("get" + fieldname, null);
			if (field[i].getType() == int.class)
				sql += field[i].getName() + "=" + f.invoke(o, null);
			else if (f.invoke(o, null) != null)
				sql += field[i].getName() + "='" + f.invoke(o, null) + "'";
			else
				continue;
			if (i == field.length - 1)
				break;
			sql += ",";
		}
		// sql += field[field.length-1].getName() + ")";
		// sql += "= (";
		// for(int i=1 ; i<field.length-1 ; ++i)
		// {
		// sql += "?,";
		// }
		if (field.length == 0)
			return 0;
		String fieldname = field[0].getName();
		char c = fieldname.charAt(0);
		fieldname = (c + "").toUpperCase() + fieldname.substring(1);
		Method f = o.getClass().getDeclaredMethod("get" + fieldname, null);
		System.out.println("fieldname:"+fieldname+" method "+f.getName());
		sql += " WHERE " + field[0].getName() + " = "
				+ f.invoke(o, null);

		System.out.println("sql update --> " + sql);

		// for (int i = 1; i < methods.length; ++i) {
		// Method f = methods[i];
		// if (f.getName().startsWith("get")
		// // && f.getName().indexOf("Cardid") == -1
		// && f.getParameterTypes().length == 0
		// && f.getName().indexOf("Class") == -1) {
		// try {
		// System.out.println((cc++) + " : " + f.getName());
		// params.add(f.invoke(o, null));
		// } catch (IllegalArgumentException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IllegalAccessException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (InvocationTargetException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// } else
		// System.out.println("aasdfasdf " + f.getName());
		// }

		int count = super.executeSQL(sql, null);
		return count;
	}

	protected void populateVO(Object bean, ResultSet rs) throws SQLException,
			IllegalArgumentException, IllegalAccessException,
			InvocationTargetException, SecurityException, NoSuchMethodException {
		/*
		 * bean.setId(rs.getInt("id")); bean.setName(rs.getString("name"));
		 * bean.setEmail(rs.getString("email"));
		 */
		Field field[] = bean.getClass().getDeclaredFields();
		Method f = null;
		// System.out.println("methods len " + methods.length);
		for (int i = 0; i < field.length; i++) {
			String fieldname = field[i].getName();
			char c = fieldname.charAt(0);
			fieldname = (c + "").toUpperCase() + fieldname.substring(1);
			f = bean.getClass().getDeclaredMethod("set" + fieldname,field[i].getType());
			//System.out.println("Get Method Name  "+f.getName());
			if (field[i].getType() == int.class) {
				f.invoke(bean, rs.getInt(field[i].getName()));
			}
			if (field[i].getType() == Date.class) {
				f.invoke(bean, rs.getDate(field[i].getName()));
			}
			if (field[i].getType() == float.class) {
				f.invoke(bean, rs.getFloat(field[i].getName()));
			}
			if (field[i].getType() == String.class) {
				f.invoke(bean, rs.getString(field[i].getName()));
			}
		}

	}

}
